package com.yonyou.pmclouds.businessobject.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.consts.EnableStatusConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.billtype.entity.BillTypeVO;
import com.yonyou.pmclouds.billtype.rmiitf.BillTypeQuery;
import com.yonyou.pmclouds.businessobject.PrintService;
import com.yonyou.pmclouds.businessobject.entity.BoAttrsVO;
import com.yonyou.pmclouds.businessobject.entity.BusinessObjectVO;
import com.yonyou.pmclouds.businessobject.entity.ProcessBoAttrsVO;
import com.yonyou.pmclouds.businessobject.rmiitf.BusinessObjectMaintain;
import com.yonyou.pmclouds.businessobject.util.BusinessObjectConfig;
import com.yonyou.pmclouds.businessobject.util.BusinessObjectConsts;
import com.yonyou.pmclouds.businessobject.util.DeepCloneUtils;
import com.yonyou.pmclouds.procedure.entity.ProcedureVO;
import com.yonyou.pmclouds.procedure.rmiitf.ProcedureQuery;
import com.yonyou.pmclouds.workquality.entity.WorkqualityDetailVO;
import com.yonyou.pmclouds.workquality.entity.WorkqualityVO;
import com.yonyou.pmclouds.workquality.service.rmiitf.WorkqualityQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.security.MessageDigest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.yonyou.pmclouds.businessobject.util.BusinessObjectConsts.*;

@Slf4j
@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = BusinessObjectMaintain.class, timeout = 80000)
public class BusinessObjectMaintainImpl implements BusinessObjectMaintain {

    @Value("${print.businessObject.specialExtendTenant}")
    private String extendTenants;

    @Autowired
    private WorkqualityQueryService workqualityQueryService;

    @Autowired
    private ProcedureQuery procedureQuery;

    @Autowired
    private BillTypeQuery billTypeQuery;

    @Override
    public String initBO(String tenantId) throws BusinessException {
        List<BusinessObjectVO> businessObjectVOS = billTypeQuery.constructBusinessObjsRelation(tenantId);
        extendBOByTenant(businessObjectVOS, tenantId);
        return this.initBO(businessObjectVOS, tenantId);
    }

    /**
     * 业务对象初始化方法
     *
     * @param businessObjectVOS 需要初始化的参数
     * @param tenantId          租户ID
     * @return 初始化结果
     */
    public String initBO(List<BusinessObjectVO> businessObjectVOS, String tenantId) throws BusinessException {
        long startTime = System.currentTimeMillis();
        int insertCount = 0;
        int updateCount = 0;
        int failCount = 0;
        StringBuilder failReasonBuilder = new StringBuilder("失败原因:");
        for (BusinessObjectVO businessObjectVO : businessObjectVOS) {
            // 如果租户为空，则初始化的为系统业务对象，否为租户级别业务对象
            if (!StringUtils.isEmpty(tenantId)) {
                businessObjectVO.setTenant_id(tenantId);
            }
            String boCode = businessObjectVO.getBo_code();
            // 获取保存业务对象Json格式数据
            String boStr = this.parseBO(businessObjectVO);
            // 保存业务对象至云打印

            String saveRet = this.saveBoToCloud(boCode, boStr, tenantId);
            Map retMap = JSON.parseObject(saveRet, Map.class);
            String message = (String) retMap.get(MESSAGE);
            int status = (int) retMap.get(RET_STATUS);
            if (status == SUCCESS) {
                //保存成功
                insertCount++;
            } else if ("bocode已存在！".equalsIgnoreCase(message)) {
                //如果存在则更新
                String updateRet = this.updateBoToCloud(boCode, boStr, tenantId);
                if (updateRet != null) {
                    retMap = JSON.parseObject(updateRet, Map.class);
                    status = (int) retMap.get(RET_STATUS);
                    if (status == SUCCESS) {
                        updateCount++;
                    } else {
                        failCount++;
                        failReasonBuilder.append(boCode).append(":").append(retMap.get(MESSAGE)).append(",");
                    }
                } else {
                    failCount++;
                    failReasonBuilder.append(boCode).append(":").append("updateRet is null").append(",");
                }
            } else {
                failCount++;
                failReasonBuilder.append(boCode).append(":").append(message).append(",");
            }
        }
        long endTime = System.currentTimeMillis();
        String result = "初始化业务对象共" + businessObjectVOS.size() + "条,总耗时" + (endTime - startTime) + "ms，插入"
                + insertCount + "条，更新" + updateCount + "条，失败" + failCount + "条";
        if (failCount > 0) {
            result = result + "," + failReasonBuilder.toString();
        }
        return result;
    }

    @Override
    public String saveBo(BusinessObjectVO businessObjectVO, String tenantId) throws BusinessException {
        String boCode = businessObjectVO.getBo_code();
        String boStr = this.parseBO(businessObjectVO);
        return saveBoToCloud(boCode, boStr, tenantId);
    }

    @Override
    public String parseBO(BusinessObjectVO businessObjectVO) throws BusinessException {
        ArrayList<BoAttrsVO> attrsVOS = businessObjectVO.getBo_attrs() == null ? this.getAttrsVo(businessObjectVO)
                : businessObjectVO.getBo_attrs();
        if (attrsVOS != null && attrsVOS.size() > 0) {
            Map<String, ArrayList<BoAttrsVO>> boMap = new HashMap<>();
            for (BoAttrsVO attrsVO : attrsVOS) {
                // 将fieldOptionMap置空，该字段配置项为云审批专用
                attrsVO.setFieldOptionMap(null);
                String boCode = attrsVO.getBo_code();
                ArrayList<BoAttrsVO> boAttrsVOS = boMap.get(boCode);
                if (boAttrsVOS != null && boAttrsVOS.size() > 0) {
                    boAttrsVOS.add(attrsVO);
                } else {
                    boAttrsVOS = new ArrayList<>();
                    boAttrsVOS.add(attrsVO);
                    boMap.put(boCode, boAttrsVOS);
                }
            }
            this.setAttrsToBO(businessObjectVO, boMap);
        }
        Map<String, BusinessObjectVO> map = new HashMap<>();
        map.put("bo", businessObjectVO);
        return JSON.toJSONString(map);
    }

    /**
     * 查询该租户的业务对象模版，配置表头字段信息
     */
    @Override
    public ArrayList<BoAttrsVO> getAttrsVo(BusinessObjectVO businessObjectVO) throws BusinessException {
        ArrayList<String> tableNameList = new ArrayList<>();
        this.getAllTableName(businessObjectVO, tableNameList);
        ArrayList<BoAttrsVO> attrsVOS = null;
        if (tableNameList.size() > 0) {
            BusinessObjectConfig boConfig = new BusinessObjectConfig(BUSINESS_OBJECT_FILE_PATH, tableNameList,
                    BillTypeVO.DATA_USAGE_PRINT);
            attrsVOS = boConfig.getBoAttrsVOS();
        }

        return attrsVOS;
    }

    private void getAllTableName(BusinessObjectVO businessObjectVO, ArrayList<String> tableNameList) {
        String tableName = businessObjectVO.getBo_code();
        ArrayList<BusinessObjectVO> subBos = businessObjectVO.getSub_bos();
        if (!StringUtils.isEmpty(tableName)) {
            tableNameList.add(tableName);
        }
        if (subBos != null && subBos.size() > 0) {
            for (BusinessObjectVO subBo : subBos) {
                this.getAllTableName(subBo, tableNameList);
            }
        }
    }

    private void setAttrsToBO(BusinessObjectVO businessObjectVO, Map<String, ArrayList<BoAttrsVO>> boMap) {
        businessObjectVO.setBo_attrs(boMap.get(businessObjectVO.getBo_code()));
        ArrayList<BusinessObjectVO> subBos = businessObjectVO.getSub_bos();
        if (subBos != null && subBos.size() > 0) {
            for (BusinessObjectVO subBo : subBos) {
                this.setAttrsToBO(subBo, boMap);
            }
        }
    }

    public String getPrintCode(String boCode, String tenantId) throws BusinessException {
        return PrintService.getPrintCode(boCode, tenantId);
    }

    @Override
    public String getPrintCodeByType(String tenantId, String billType, String pkProcedure) throws BusinessException {
        // 判断是否该租户是否需要支持特殊工序模版配置
        String boCode = "";
        BillTypeVO billTypeVO = billTypeQuery.queryBillByType(billType, "datumManage");
        boCode = billTypeVO == null ? "" : billTypeVO.getTableName();
        // 目前只支持巡查记录、旁站记录、平行检验、施工记录使用工序模版，其余使用单据模版
        if(BillTypeConst.PATROL_BILLTYPE.equalsIgnoreCase(billType) ||
                BillTypeConst.CONSTRUCTIONLOG_BILLTYPE.equalsIgnoreCase(billType) ||
                BillTypeConst.PARALLEL_INSPECTION_BILLTYPE.equalsIgnoreCase(billType) ||
                BillTypeConst.SIDE_INSPECTION_BILLTYPE.equalsIgnoreCase(billType)){
            if (StringUtils.isNotEmpty(extendTenants) && extendTenants.contains(tenantId) && StringUtils.isNotEmpty(pkProcedure)) {
                ProcedureVO procedureVO = procedureQuery.getById(pkProcedure);
                if (procedureVO != null) {
                    String procedureCode = procedureVO.getScode();
                    // 找不到工序模版，则查找对应的单据模版
                    String printCode = PrintService.getPrintCode(procedureCode, tenantId);
                    if(StringUtils.isNotEmpty(printCode)){
                        return printCode;
                    }
                }
            }
        }
        String printCode = PrintService.getPrintCode(boCode, tenantId);
        if(StringUtils.isEmpty(printCode)){
            throw new BusinessException("该单据未找到模版，请先配置打印模版！");
        }
        return printCode;

    }

    @Override
    public String getPrintCodeByProcessCode(String processCode, String tenantId) throws BusinessException {
        if(StringUtils.isEmpty(processCode)){
            return null;
        }

        String printCode = PrintService.getPrintCode(processCode, tenantId);
        if(StringUtils.isNotEmpty(printCode)){
            return printCode;
        }

        return null;
    }

    public String initTenantBizz(List<String> tenantIdList) throws BusinessException {
        if (tenantIdList == null || tenantIdList.size() <= 0) {
            return null;
        }
        for (String tenantId : tenantIdList) {
            if (StringUtils.isEmpty(tenantId)) {
                continue;
            }

            /**
            //初始化复制之前先删除该租户下所有模版，再删除所有业务对象
            String result = "";
            ArrayList<JSONObject> jsonObjects = this.getTemplateByTenantId(tenantId);
            if (!jsonObjects.isEmpty()) {
                for (JSONObject jsonObject : jsonObjects) {
                    String pkTemplate = jsonObject.getString("pk_print_template");
                    result = this.deleteTemplate(pkTemplate, tenantId);
                    Map<String, Object> rtnMap = JSON.parseObject(result, Map.class);
                    if (!(boolean) rtnMap.get("delresult")) {
                        return result;
                    }
                }
            }
            jsonObjects = this.getBoByTenantId(tenantId);
            if (!jsonObjects.isEmpty()) {
                for (JSONObject jsonObject : jsonObjects) {
                    String pkBo = jsonObject.getString("pk_bo");
                    result = this.deleteBo(pkBo, tenantId);
                    Map<String, Object> rtnMap = JSON.parseObject(result, Map.class);
                    if (!(boolean) rtnMap.get("deleteResult")) {
                        return result;
                    }
                }
            }

             **/
            initTenantFromCloud(tenantId);
        }

        return "初始化成功";
    }

    private ArrayList<JSONObject> getTemplateByTenantId(String tenantId) throws BusinessException {
        return PrintService.getTemplateByTenantId(tenantId);
    }

    private String initTenantFromCloud(String tenantId) throws BusinessException {
        return PrintService.initTenantFromCloud(tenantId);
    }

    private String deleteTemplate(String pkTemplate, String tenantId) {
        return PrintService.deleteTemplate(pkTemplate, tenantId);
    }

    private ArrayList<JSONObject> getBoByTenantId(String tenantId) throws BusinessException {
        return PrintService.getBoByTenantId(tenantId);
    }

    private String deleteBo(String pkBo, String tenantId) throws BusinessException {
        return PrintService.deleteBo(pkBo, tenantId);
    }

    /**
     * 保存业务对象到云审批
     *
     * @param boCode   业务对象编码
     * @param boStr    业务对象结构数据
     * @param tenantId 租户ID
     * @return 保存结果
     */
    private String saveBoToCloud(String boCode, String boStr, String tenantId) throws BusinessException {
        return PrintService.saveBoToCloud(boCode, boStr, tenantId);
    }

    /**
     * 更新业务对象到云审批
     *
     * @param boCode   业务对象编码
     * @param boStr    业务对象结构数据
     * @param tenantId 租户ID
     * @return 保存结果
     */
    public String updateBoToCloud(String boCode, String boStr, String tenantId) throws BusinessException {
        return PrintService.updateBoToCloud(boCode, boStr, tenantId);
    }

    /**
     * 特殊租户业务对象扩展
     *
     * @param businessObjectVOS 业务对象集合
     * @param tenantId          租户ID
     */
    private void extendBOByTenant(List<BusinessObjectVO> businessObjectVOS, String tenantId) throws BusinessException {
        // 判断是否该租户是否需要支持特殊工序模版配置
        if (StringUtils.isEmpty(tenantId) || StringUtils.isEmpty(extendTenants) || !extendTenants.contains(tenantId)) {
            return;
        }

        // 查询该租户下所有启动状态的工序
        ProcedureVO[] procedureVOS = procedureQuery.queryProcedureByTenant(tenantId, EnableStatusConst.ENABLE);
        if (procedureVOS == null || procedureVOS.length <= 0) {
            return;
        }

        Set<String> pkProcedureSet = new HashSet<>();
        Map<String, ProcedureVO> procedureVOMap = new HashMap<>();
        for (ProcedureVO procedureVO : procedureVOS) {
            pkProcedureSet.add(procedureVO.getPkProcedure());
            procedureVOMap.put(procedureVO.getPkProcedure(), procedureVO);
        }

        // 查询工序下的检查标准
        Map<String, List<WorkqualityVO>> newWorkQualityMap = this.getBOByProcedure(pkProcedureSet);
        if (newWorkQualityMap == null) {
            return;
        }

        BusinessObjectVO businessObjectVO = new BusinessObjectVO();
        businessObjectVO.setBo_code(BusinessObjectConsts.PM_PROCESS_FEATURE);
        businessObjectVO.setTenant_id(tenantId);
        // 查询特殊工序的业务对象模版
        ArrayList<BoAttrsVO> attrsVOS = this.getAttrsVo(businessObjectVO);

        // 一个工序构造一套业务对象
        for (Map.Entry<String, List<WorkqualityVO>> entry : newWorkQualityMap.entrySet()) {
            ProcedureVO procedureVO = procedureVOMap.get(entry.getKey());
            String procedureName = filterSpecialChar(procedureVO.getSname());
            List<WorkqualityVO> workQualityVOList = entry.getValue();
            BusinessObjectVO bo = new BusinessObjectVO();
            bo.setTenant_id(tenantId);
            bo.setBo_code(procedureVO.getScode());
            bo.setBo_name(procedureName);

            ArrayList<BoAttrsVO> newAttrList = getBoAttrsVOByQuality(workQualityVOList, bo);
            List<BoAttrsVO> attrsVOSCopy = DeepCloneUtils.depCopy(attrsVOS);
            if (attrsVOSCopy != null) {
                for (BoAttrsVO boAttrsVO : attrsVOSCopy) {
                    boAttrsVO.setBo_code(procedureVO.getScode());
                    boAttrsVO.setBo_name(procedureName);
                    newAttrList.add(boAttrsVO);
                }
            }
            bo.setBo_attrs(newAttrList);
            businessObjectVOS.add(bo);
        }

    }

    /**
     * 根据工序主键查询测试数据字段信息
     *
     * @param pkProcedure 工序主键
     * @return key为检查项主键，value为字段编码
     */
    @Override
    public Map<String, List<String>> getAttrByProcedure(String pkProcedure) throws BusinessException {
        Map<String, List<String>> attributeMap = new HashMap<>();
        Set<String> pkProcedureSet = new HashSet<>();
        pkProcedureSet.add(pkProcedure);
        Map<String, List<WorkqualityVO>> newWorkQualityMap = this.getBOByProcedure(pkProcedureSet);
        if (newWorkQualityMap == null) {
            return null;
        }

        for (Map.Entry<String, List<WorkqualityVO>> entry : newWorkQualityMap.entrySet()) {
            List<WorkqualityVO> qualityVOS = entry.getValue();
            Map<String, ProcessBoAttrsVO> detailVOMap = this.getQualityDetails(qualityVOS);
            for (Map.Entry<String, ProcessBoAttrsVO> detailVOEntry : detailVOMap.entrySet()) {
                WorkqualityDetailVO detailVO = detailVOEntry.getValue().getDetailVO();
                attributeMap.put(detailVO.getPkWorkqualitydetail(),
                        this.getDataFieldByDetail(detailVOEntry.getValue().getAttributeKey()));
            }
        }

        return attributeMap;
    }

    /**
     * 查询工序下的检查标准
     *
     * @param pkProcedureSet 工序集合
     * @return 检查标准集合
     */
    private Map<String, List<WorkqualityVO>> getBOByProcedure(Set<String> pkProcedureSet) throws BusinessException {


        // 查询工序下的所有检查标准，一个工序可能对应多个检查标准
        List<WorkqualityVO> workQualityVOS = workqualityQueryService.queryByPkProcedures(pkProcedureSet);
        if (workQualityVOS == null || workQualityVOS.size() <= 0) {
            return null;
        }

        Set<String> pkWorkQualitySet = new HashSet<>();
        Map<String, WorkqualityVO> workQualityVOMap = new HashMap<>();
        for (WorkqualityVO workqualityVO : workQualityVOS) {
            pkWorkQualitySet.add(workqualityVO.getPkWorkquality());
            workQualityVOMap.put(workqualityVO.getPkWorkquality(), workqualityVO);
        }

        // 查询检查标准下的检查项
        List<WorkqualityDetailVO> detailVOList = workqualityQueryService.queryDetailByPkQualities(pkWorkQualitySet);

        if (detailVOList == null || detailVOList.size() <= 0) {
            return null;
        }

        Map<String, List<WorkqualityDetailVO>> detailVOMap = new HashMap<>();
        for (WorkqualityDetailVO detailVO : detailVOList) {
            if (detailVOMap.get(detailVO.getPkWorkquality()) != null) {
                detailVOMap.get(detailVO.getPkWorkquality()).add(detailVO);
            } else {
                List<WorkqualityDetailVO> detailVOS = new ArrayList<>();
                detailVOS.add(detailVO);
                detailVOMap.put(detailVO.getPkWorkquality(), detailVOS);
            }
        }

        Map<String, List<WorkqualityVO>> newWorkQualityMap = new HashMap<>();
        for (Map.Entry<String, List<WorkqualityDetailVO>> entry : detailVOMap.entrySet()) {
            WorkqualityVO workqualityVO = workQualityVOMap.get(entry.getKey());
            workqualityVO.setItemtabledata(entry.getValue().toArray(new WorkqualityDetailVO[]{}));
            if (newWorkQualityMap.get(workqualityVO.getPkProcedure()) != null) {
                newWorkQualityMap.get(workqualityVO.getPkProcedure()).add(workqualityVO);
            } else {
                List<WorkqualityVO> qualityVOs = new ArrayList<>();
                qualityVOs.add(workqualityVO);
                newWorkQualityMap.put(workqualityVO.getPkProcedure(), qualityVOs);
            }
        }

        return newWorkQualityMap;


    }

    /**
     * 根据检查标准构造测试数据字段
     *
     * @param workQualityVOList 检查标准集合
     */
    private ArrayList<BoAttrsVO> getBoAttrsVOByQuality(List<WorkqualityVO> workQualityVOList, BusinessObjectVO bo) throws BusinessException {
        ArrayList<BoAttrsVO> boAttrsVOS = new ArrayList<>();
        Map<String, ProcessBoAttrsVO> detailVOMap = this.getQualityDetails(workQualityVOList);

        // 初始化业务对象时过滤重复的检查标准
        Map<String, WorkqualityDetailVO> newDetailVOMap = new HashMap<>();

        for (Map.Entry<String, ProcessBoAttrsVO> entry : detailVOMap.entrySet()) {
            newDetailVOMap.put(entry.getValue().getAttributeKey(), entry.getValue().getDetailVO());
        }

        for (Map.Entry<String, WorkqualityDetailVO> entry : newDetailVOMap.entrySet()) {
            String key = entry.getKey();
            WorkqualityDetailVO detailVO = entry.getValue();
            this.getBoAttrsByDetail(boAttrsVOS, detailVO, bo, key);
        }

        return boAttrsVOS;

    }

    private Map<String, ProcessBoAttrsVO> getQualityDetails(List<WorkqualityVO> workQualityVOList) throws BusinessException {
        Map<String, ProcessBoAttrsVO> detailVOMap = new HashMap<>();

        for (WorkqualityVO workqualityVO : workQualityVOList) {
            WorkqualityDetailVO[] detailVOs = workqualityVO.getItemtabledata();

            // 因为同一个工序可能存在配置相同的检查项，但是类别不一样，共用一个模版，所以根据中文进行判断是否相同
            for (WorkqualityDetailVO detailVO : detailVOs) {
                ProcessBoAttrsVO processBoAttrsVO = new ProcessBoAttrsVO();
//                String key = this.getASCIIByChinese(detailVO.getCheckitem().trim());
                String key = this.encodeByMD5(detailVO.getCheckitem().trim());
                processBoAttrsVO.setAttributeKey(key);
                processBoAttrsVO.setDetailVO(detailVO);

                detailVOMap.put(detailVO.getPkWorkqualitydetail(), processBoAttrsVO);
            }
        }

        return detailVOMap;
    }

    /**
     * 根据检查项构造测试数据字段，每个检查项构造10个字段
     *
     * @param boAttrsVOS 业务对象字段集合
     * @param detailVO   检查项数据
     * @param bo         业务对象数据
     * @param key        检查项名称
     */
    private void getBoAttrsByDetail(List<BoAttrsVO> boAttrsVOS, WorkqualityDetailVO detailVO, BusinessObjectVO bo, String key) {
        List<String> fieldCodeList = this.getDataFieldByDetail(key);
        if (fieldCodeList == null) {
            return;
        }
        for (int i = 0; i < fieldCodeList.size(); i++) {
            BoAttrsVO attrsVO = new BoAttrsVO();
            attrsVO.setIsPrimary("0");
            attrsVO.setFieldOptionMap(null);
            attrsVO.setFieldtype("char");
            attrsVO.setCode(fieldCodeList.get(i));
            String fieldName = detailVO.getCheckitem() + i;
            attrsVO.setName(filterSpecialChar(fieldName));
            attrsVO.setBo_code(bo.getBo_code());
            attrsVO.setBo_name(bo.getBo_name());

            boAttrsVOS.add(attrsVO);
        }
    }

    private String filterSpecialChar(String name){
        String regEx = "[\n`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？-]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(name);
        name = m.replaceAll("").trim().replaceAll("\t", "");
        return name;
    }

    private List<String> getDataFieldByDetail(String key) {
        List<String> fieldList = new ArrayList<>();
        /** 暂不采用此种算法
        // key + 检查项名称前9个字符对应的ascii码的第二位 + 流水号
        if (StringUtils.isEmpty(key)) {
            return null;
        }
        StringBuilder fieldCodeBuilder = new StringBuilder();
        for (int i = 1; i < key.length(); i += 5) {
            if (fieldCodeBuilder.toString().length() > 8) {
                break;
            }
            fieldCodeBuilder.append(key.charAt(i));
        }
        String fieldCode = fieldCodeBuilder.toString();
         **/
        for (int i = 0; i < 10; i++) {
            fieldList.add("key" + key + i);
        }
        return fieldList;
    }

    private String getASCIIByChinese(String chinese) {
        if (StringUtils.isEmpty(chinese)) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : chinese.toCharArray()) {
            stringBuilder.append((int) c);
        }
        return stringBuilder.toString();
    }

    private String encodeByMD5(String chinese) throws BusinessException {
        if (StringUtils.isNotEmpty(chinese)) {
            try {
                // 创建具有指定算法名称的信息摘要
                MessageDigest md = MessageDigest.getInstance("MD5");
                // 使用指定的字节数组对摘要进行最后的更新，然后完成摘要计算
                byte[] results = md.digest(chinese.getBytes());
                // 将得到的字节数组编程字符串返回
                String resultString = byteArrayToHexString(results);
                return resultString.toUpperCase();
            } catch (Exception ex) {
                throw new BusinessException("业务对象字段编码获取失败：" + ex.getMessage());
            }
        }
        return null;
    }

    // 转换字节数组为十六进制字符串
    private String byteArrayToHexString(byte[] b) {
        StringBuilder resultBuilder = new StringBuilder();
        int i = 0;
        for (i = 0; i < b.length; i++) {
            resultBuilder.append(byteToHexString(b[i]));
        }
        return resultBuilder.toString();
    }

    // 将字节转化成十六进制的字符串
    private String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = 256 + n;
        }
        int d1 = n / 16;
        int d2 = n / 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    // 16进制下数字到字符的映射数组
    private String[] hexDigits = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c",
            "d", "e", "f" };

}
